package com.itheima.web.advice;

import com.itheima.pojo.SysLog;
import com.itheima.pojo.User;
import com.itheima.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
@Aspect
public class LogAdvice {

    @Pointcut("execution(* com.itheima.web.controller.StudentController.login(..))")
    public void pt() {
    }

    @Autowired
    private LogService logService;

    /**
     * 通知
     */
    @Around("pt()")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {
        Object result = null;

        try {
            result = pjp.proceed();
        } finally {
            SysLog sysLog = new SysLog();
            //获取参数对象
            Object[] args = pjp.getArgs();
            //判断参数是否存在
            if(args != null && args.length > 0) {
                //获取第一个参数request
                Object req = args[0];
                //判断request是否存在
                if(req instanceof HttpServletRequest){
                    String remoteAddr = ((HttpServletRequest) req).getRemoteAddr();
                    sysLog.setIpAddress(remoteAddr);

                    Object userName = ((HttpServletRequest) req).getSession().getAttribute("userName");
                    if(userName == null){
                        sysLog.setLoginName("");
                    }else{
                        sysLog.setLoginName(((User)userName).getName());
                    }
                }
            }
            sysLog.setLoginTime(new Date());
            logService.save(sysLog);
        }
        return result;
    }
}
